<template>
  <div class="box-bg-color">
    <div class="filter-container">
      <div class="filter-item">
        <el-select v-model="searchReq.type" clearable style="width: 160px" placeholder="请选择栏目类型">
          <el-option label="单页" value="page">
            <k-badge type="primary" content="单页"></k-badge>
          </el-option>
          <el-option label="列表" value="list">
            <k-badge type="danger" content="列表"></k-badge>
          </el-option>
        </el-select>
      </div>
      <div class="filter-item">
        <el-input v-model="searchReq.title" placeholder="请输入栏目标题" style="width: 200px" clearable></el-input>
      </div>
      <div class="filter-item">
        <el-button type="primary" @click="searchEvent">搜索</el-button>
      </div>
      <div class="filter-action-wrapper upload-wrap">
        <div class="filter-item">
          <el-button type="primary" v-perm="'column:add'" @click="clickAddEvent">新增栏目</el-button>
        </div>
      </div>
    </div>

    <k-table
      ref="tableRef"
      v-bind="tableData"
      :loading="loading"
    >
      <template #parentId="{ row }">{{ deptMap[row.parentId] }}</template>
      <template #type="{ row }">
        <k-badge
          :type="'primary'"
          :content="row.type === 'list' ? '列表' : '单页'"
        ></k-badge>
      </template>
      <template #actions="{ row }">
        <el-button type="primary" plain size="small" @click="clickEditEvent(row.id)" v-perm="'column:edit'">编辑</el-button>
        <el-button type="info" plain size="small" @click="clickDeleteEvent(row)" v-perm="'column:delete'">删除</el-button>
      </template>
    </k-table>

    <!-- 栏目编辑 -->
    <Edit v-model="showEdit" :columnAllList="columnAllList" :curr-id="currId" @change="updateColumnSuccess"></Edit>

    <!-- 栏目添加 -->
    <Add v-model="showAdd" :columnAllList="columnAllList" @change="createColumnSuccess"></Add>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, type UploadRawFile } from 'element-plus'
import type { IKTableProps } from 'k-ui'
import { useRoute, type RouteRecordRaw, useRouter } from 'vue-router'

import appConfig from '@/config/index'
import { confirmElBox, dateStrFormat, listToTree } from '@/utils'

import {
  getColumnList,
  deleteColumn,
  getColumnAllList,
  type QueryColumnList,
  type ColumnApiResult
} from '@/api/column'

import Edit from './components/Edit.vue'
import Add from './components/add.vue'
import { hasPerms } from '@/utils/perm'

const route = useRoute()
const router = useRouter()

let routeData = reactive({
  query: route.query
})

onMounted(() => {
  if (routeData.query.isAdd === 'Y') {
    clickAddEvent()
  }
})

const tableRef = ref()
const tableData = ref<IKTableProps<ColumnApiResult>>({
  mode: 'config',
  data: { list: [] },
  isPager: false,
  rowKey: 'id',
  columns: [
    { label: '标题', prop: 'title', default: '--' },
    { label: '副标题', prop: 'subhead', default: '--' },
    { label: '上级栏目', prop: 'parentId', slot: true },
    { label: '类型', prop: 'type', slot: true, width: 100 },
    { label: '排序', prop: 'orderNum' },
    {
      label: '创建时间',
      prop: 'createDate',
      formatter: (row: ColumnApiResult) => dateStrFormat(row.createDate as string),
      width: 100
    }
  ]
})

/* 这里判断是否有整个操作列的权限；如果没有则不显示整列 */
const hasActionPerm = hasPerms(['column:edit', 'column:delete'])
hasActionPerm && tableData.value.columns.push({ label: '操作', prop: 'actions', slot: true, width: 240 })

const loading = ref<boolean>(false)

const searchReq = ref<QueryColumnList>({
  page: 1,
  size: 20,
  type: '',
  title: ''
})
// 查询表格事件
const queryReq = ref<QueryColumnList>({ page: 1, size: 20 })

const deptMap = ref<Record<string, string>>({
  '': ''
})
// 查询当前栏目
const columnAllList = ref<ColumnApiResult[]>([])
const getColumnListApi = async () => {
  loading.value = true
  const res = await getColumnAllList()
  loading.value = false
  if (res?.code === 200) {
    columnAllList.value = res.data as ColumnApiResult[]
    columnAllList.value.unshift({ id: '0', title: '一级栏目' })
    let data = res.data as ColumnApiResult[]
    data.forEach((v) => {
      deptMap.value[v.id] = v.title as string
    })
    data = listToTree(data, { root: '0', pidKey: 'parentId' })
    tableData.value.data.list = data
  } else {
    ElMessage({ message: res?.msg || '网络异常，请稍后重试', type: 'error' })
  }
}

getColumnListApi();

const updateColumnSuccess = (newPage = {}) => {
  getColumnListApi();
}

const createColumnSuccess = (newPage = {}) => {
  getColumnListApi();
}

const searchEvent = () => {
  queryReq.value = Object.assign({}, searchReq.value)
  updateColumnSuccess({ page: 1, size: 10 })
}

// 栏目编辑
const showEdit = ref<boolean>(false)
const currId = ref<string | undefined>(undefined)
const clickEditEvent = (id: string) => {
  currId.value = id
  showEdit.value = true
}

// 栏目添加
const showAdd = ref<boolean>(false)
const clickAddEvent = () => {
  showAdd.value = true
}

const clickDeleteEvent = async (row: ColumnApiResult) => {
  confirmElBox(`是否确认将栏目【${row.title}】删除吗？`, async () => {
    loading.value = true
    const res = await deleteColumn({ id: row.id, isDelete: 0 })
    loading.value = false
    if (res?.code === 200) {
      ElMessage({ type: 'success', message: `删除成功` })
      updateColumnSuccess()
    } else {
      ElMessage({ type: 'error', message: res?.msg || '网络异常，请稍后重试！' })
    }
  })
}

</script>

<style lang="scss" scoped>
.user-account-wrap {
  display: flex;
  align-items: center;
  padding: 0 10px;
}

.upload-wrap {
  display: flex;
}
</style>
